package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.Them;
import com.sk.bilibili.dto.FollowThemInfo;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.FollowThem;
import com.sk.bilibili.mapper.FollowThemMapper;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 邵康
* @date 2021/11/24 09:40
*/
@Service
public class FollowThemService extends ServiceImpl<FollowThemMapper,FollowThem> {

    @Autowired
    private ThemService themService;

    public R<FollowThem> add(FollowThem followThem) {
        followThem.setMemberId(BSessionUtils.getMemberId());
        save(followThem);
        return R.success(followThem);
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(FollowThem followThem) {
        updateById(followThem);
        return R.success();
    }

    public R<IPage<FollowThem>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page,size),null));
    }

    public R<IPage<FollowThem>> getFollowThem(FollowThemInfo followThemInfo) {
        if(followThemInfo.getMemberId()==null)followThemInfo.setMemberId(BSessionUtils.getMemberId());
        Page<FollowThem> page = baseMapper.getFollowThem(followThemInfo.page(), followThemInfo, followThemInfo.getMemberId());
        page.getRecords().forEach(this::warpFollowThem);
        return R.success(page);
    }

    private void warpFollowThem(FollowThem followThem) {
        followThem.getExtra().addExtra(themService.getWarpThem(followThem.getThemId()));
    }

    public R<Void> updateState(Integer id, Integer state) {
        if(state==null){
            removeById(id);
        }else {
            FollowThem followThem = new FollowThem();
            followThem.setId(id);
            followThem.setState(state);
            updateById(followThem);
        }
        return R.success();
    }

    public void warpFollowState(int memberId, Them them) {
        QueryWrapper<FollowThem> queryWrapper = QueryWrapperUtils.eq("them_id",
                them.getId(), "member_id", memberId);
        them.getExtra().put("followThem",getOne(queryWrapper));
    }

    public List<Integer> getFollowThemId(int memberId) {
        QueryWrapper<FollowThem> queryWrapper = QueryWrapperUtils.eq("member_id", memberId);
        queryWrapper.select("them_id");
        return list(queryWrapper).stream().map(FollowThem::getThemId).collect(Collectors.toList());
    }

}
